package com.example.understandvideo.service.transcode;

import com.example.understandvideo.service.CommonService;
import com.example.understandvideo.tool.HttpTool;
import com.example.understandvideo.tool.IdWorkerUtils;
import com.example.understandvideo.tool.XMLUtil;
import com.github.jknack.handlebars.Handlebars;
import com.github.jknack.handlebars.Template;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.util.UriTemplate;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class TranscodeService {
    @Resource
    private CommonService commonService;

    /**
     * 多段裁剪
     *
     * @param targetPath
     * @param clipDataList
     * @return
     */
    public CutCloudTaskResponse sendCutCloudTask(String targetPath, List<ClipData> clipDataList) {
        CutCloudTaskResponse result = new CutCloudTaskResponse();
        String targetFilename = String.valueOf(IdWorkerUtils.nextId());
        String taskName = "马拉松裁剪任务-" + targetFilename;
        String xmlString = getXmlTask(taskName, clipDataList, targetPath, targetFilename);
        String response = HttpTool.postXmlStr(xmlString, commonService.getServerAddress() + "/api/task/launch");
        CloudCutTask resultTask = (CloudCutTask) XMLUtil.convertXmlStrToObject(CloudCutTask.class, response);
        String idString = resultTask.getId();
        if (StringUtils.isNotEmpty(idString)) {
            result.setCloudId(Long.valueOf(idString));
            result.setTargetPath(targetPath + targetFilename + ".mp4");
        }
        return result;
    }

    /**
     * 多段裁剪
     *
     * @param times
     * @param filepath
     * @param targetPath
     * @return
     */
    public CutCloudTaskResponse sendCutCloudTaskOne(List<TimeSlice> times, String filepath, String targetPath) {

        CutCloudTaskResponse result = new CutCloudTaskResponse();
        //生成数据对象
        String targetFilename = String.valueOf(IdWorkerUtils.nextId());
        String taskName = "马拉松单段裁剪任务-" + targetFilename;
        CloudCutTask targetTask = CloudTargetMakerTool.getDefaultVCutByTimeObject(taskName, filepath, times, targetPath, targetFilename);
        //XMLUtil.convertToXml(targetTask,"D:\\项目列表\\二创crts\\转码xml测试\\多端裁剪 - task -1.xml");
        String xmlString = XMLUtil.convertToXml(targetTask);
        String response = HttpTool.postXmlStr(xmlString, commonService.getServerAddress() + "/api/task/launch");
        CloudCutTask resultTask = (CloudCutTask) XMLUtil.convertXmlStrToObject(CloudCutTask.class, response);
        String idString = resultTask.getId();
        if (StringUtils.isNotEmpty(idString)) {
            result.setCloudId(Long.valueOf(idString));
            result.setTargetPath(targetPath + File.separator + targetFilename + ".mp4");
        }
        return result;
    }

    /**
     * 多段裁剪
     *
     * @param times
     * @param filepath
     * @param targetPath
     * @return
     */
    public CutCloudTaskResponse sendCommonCloudTask(List<TimeSlice> times, String filepath, String targetPath, String name) {

        CutCloudTaskResponse result = new CutCloudTaskResponse();
        //生成数据对象
        String targetFilename = String.valueOf(IdWorkerUtils.nextId());
        String taskName = name + "-" + targetFilename;
        CloudCutTask targetTask = CloudTargetMakerTool.getDefaultVCutByTimeObject(taskName, filepath, times, targetPath, targetFilename);
        //XMLUtil.convertToXml(targetTask,"D:\\项目列表\\二创crts\\转码xml测试\\多端裁剪 - task -1.xml");
        String xmlString = XMLUtil.convertToXml(targetTask);
        String response = HttpTool.postXmlStr(xmlString, commonService.getServerAddress() + "/api/task/launch");
        CloudCutTask resultTask = (CloudCutTask) XMLUtil.convertXmlStrToObject(CloudCutTask.class, response);
        String idString = resultTask.getId();
        if (StringUtils.isNotEmpty(idString)) {
            result.setCloudId(Long.valueOf(idString));
            result.setTargetPath(targetPath + File.separator + targetFilename + ".mp4");
        }
        return result;
    }

    private String getXmlTask(String taskName, List<ClipData> clipDataList, String targetDir, String targetFilename) {
        String uri = "";
        String clip = "";
        int i = 0;
        for (ClipData clipData : clipDataList) {
            if (i == 0) {
                uri = clipData.getClipFilePath();
                i++;
            } else {
                clip = clip +
                        "<clip >\n" +
                        "                    <entrymode>-1</entrymode>\n" +
                        "                \t<entry>" + clipData.getClipInsertTime() + "</entry>\n" +
                        "                    <uri>" + clipData.getClipFilePath() + "</uri>\n" +
                        "                    <programid>0</programid>\n" +
                        "                    <audiotrackid>2</audiotrackid>\n" +
                        "                    <subtitleid>-3</subtitleid>\n" +
                        "                    <cropping>0</cropping>\n" +
                        "                    <start>" + clipData.getClipStartTime() + "</start>\n" +
                        "                    <end>" + clipData.getClipStopTime() + "</end>  \n" +
                        "        <drm>\n" +
                        "            <type>ARC</type>\n" +
                        "            <enabled>0</enabled>\n" +
                        "            <version>1</version>\n" +
                        "            <contentid></contentid>\n" +
                        "            <customerid></customerid>\n" +
                        "        </drm>\n" +
                        "                </clip>\n";
            }
        }
        String result = "<task id=\"1\" href=\"/api/task/1\">\n" +
                "<name>" + taskName + "</name>\n" +
                "<description></description>\n" +
                "<encodingoption>Custom</encodingoption>\n" +
                "<priority>5</priority>\n" +
                "<gpuid>-1</gpuid>\n" +
                "<videodecoding>0</videodecoding>\n" +
                "    <videodecoderthread>-1</videodecoderthread>\n" +
                "    <preprocessmode>0</preprocessmode>\n" +
                "    <preprocessthread>-1</preprocessthread>\n" +
                "    <transcodingtype>-1</transcodingtype>\n" +
                "    <fileanalyzetype>0</fileanalyzetype>\n" +
                "<status>COMPLETED</status>\n" +
                "<streams>\n" +
                "    <stream id=\"-1\">\n" +
                "        <h264 id=\"-1\">\n" +
                "            <profile>High</profile>\n" +
                "            <level>-1</level>\n" +
                "            <width>720</width>\n" +
                "            <height>576</height>\n" +
                "            <par>source</par>\n" +
                "            <par_x>-1</par_x>\n" +
                "            <par_y>-1</par_y>\n" +
                "            <fr>source</fr>\n" +
                "            <fr_x>-1</fr_x>\n" +
                "            <fr_y>-1</fr_y>\n" +
                "            <interpolate>1</interpolate>\n" +
                "            <frameratesourcemode>0</frameratesourcemode>\n" +
                "            <playratemode>-1</playratemode>\n" +
                "            <markid>5747440</markid>\n" +
                "            <rc>VBR</rc>\n" +
                "            <bitrate>1000</bitrate>\n" +
                "            <maxbitrate>3000</maxbitrate>\n" +
                "            <cqquantizer>0</cqquantizer>\n" +
                "            <transform8x8>1</transform8x8>\n" +
                "            <intraprediction8x8>1</intraprediction8x8>\n" +
                "            <bufsize>375</bufsize>\n" +
                "            <buffillpct>1000</buffillpct>\n" +
                "            <gopsize>100</gopsize>\n" +
                "            <goptype>0</goptype>\n" +
                "            <gopmodeid>1</gopmodeid>\n" +
                "            <scd>0</scd>\n" +
                "            <bframe>0</bframe>\n" +
                "            <bitdepth>8</bitdepth>\n" +
                "                <chromasampling>420</chromasampling>\n" +
                "            <cabac>1</cabac>\n" +
                "            <refframe>1</refframe>\n" +
                "            <interlace>-1</interlace>\n" +
                "                <threadcount>5</threadcount>\n" +
                "                <lookheadframe>20</lookheadframe>\n" +
                "                <frcmode>0</frcmode>\n" +
                "            <smartborder>1</smartborder>\n" +
                "                <twopass>0</twopass>\n" +
                "                <deviceid>0</deviceid>\n" +
                "                <qualitylevel>2</qualitylevel>\n" +
                "                <caequalitylevel>1</caequalitylevel>\n" +
                "            <HdrType>CUSTOM</HdrType>\n" +
                "            <colorprimaries>0</colorprimaries>\n" +
                "            <luminancerange>0</luminancerange>\n" +
                "            <simhd>\n" +
                "    <deblock>0</deblock>\n" +
                "                <deinterlace>2</deinterlace>\n" +
                "                <denoise>0</denoise>\n" +
                "                <denoisemethod>0</denoisemethod>\n" +
                "                <delight>0</delight>\n" +
                "                <sharpen>0</sharpen>\n" +
                "                    <dehaze>0</dehaze>\n" +
                "                <antialias>0</antialias>\n" +
                "                <antishaking>-1</antishaking>\n" +
                "                    <lumaMode>0</lumaMode>\n" +
                "                <brightness>0</brightness>\n" +
                "                <contrast>0</contrast>\n" +
                "                <saturation>0</saturation>\n" +
                "                <hue>0</hue>\n" +
                "                    <resizealg>3</resizealg>\n" +
                "                    <deinterlacealg>3</deinterlacealg>\n" +
                "                    <autocolor>-1</autocolor>\n" +
                "                    <p000>1.0</p000>\n" +
                "                    <p001>1.0</p001>\n" +
                "                    <p002>1.0</p002>\n" +
                "                    <airesize>0</airesize>\n" +
                "                    <aienhancement>0</aienhancement>\n" +
                "                    <aideblurring>0</aideblurring>\n" +
                "            </simhd>\n" +
                "            <preprocessor>\n" +
                "                <motioniconbegin></motioniconbegin>\n" +
                "                <dynamictextbegin></dynamictextbegin>\n" +
                "            </preprocessor>\n" +
                "        </h264>\n" +
                "        <aac>\n" +
                "            <profile>LC</profile>\n" +
                "            <packagemode>1</packagemode>\n" +
                "<channel>2</channel>\n" +
                "    <bitrate>64000</bitrate>\n" +
                "<samplerate>32000</samplerate>\n" +
                "<denoise>0</denoise>\n" +
                "<volumemode>0</volumemode>\n" +
                "<balancedb>-30</balancedb>\n" +
                "<balancelevel>0</balancelevel>\n" +
                "<boostlevel>0</boostlevel>\n" +
                "<channelprocessing>None</channelprocessing>\n" +
                "            <playratemode>-1</playratemode>\n" +
                "            <language></language>\n" +
                "            <joinedref></joinedref>            \n" +
                "        </aac>\n" +
                "    </stream>\n" +
                "</streams>\n" +
                "<inputs>\n" +
                "    <localfile>\n" +
                "        <uri>" + uri + "</uri>\n" +
                "        <programid>0</programid>\n" +
                "        <audiotrackid>2</audiotrackid>\n" +
                "        <subtitleid>-3</subtitleid>\n" +
                "        <audiochannelid>-1</audiochannelid>\n" +
                "        <audiotrackids>2</audiotrackids>\n" +
                "        <filltype>0</filltype>\n" +
                "        <skiprotation>0</skiprotation>\n" +
                "        <skiperror>0</skiperror>\n" +
                "    <input3dtype>0</input3dtype>\n" +
                "        <videooutputmode>0</videooutputmode>\n" +
                "        <SubtitleInfo>\n" +
                "            <subtitletype></subtitletype>\n" +
                "            <language></language>\n" +
                "        </SubtitleInfo>\n" +
                "<dolbyDecoder>\n" +
                "            <enabled>0</enabled>\n" +
                "        <drcMode>2</drcMode>\n" +
                "        <drcBoost>100</drcBoost>\n" +
                "        <drcCut>100</drcCut>\n" +
                "        <dmxMode>0</dmxMode>\n" +
                "</dolbyDecoder>\n" +
                "<VideoMetadata>\n" +
                "            <vividuri></vividuri>\n" +
                "</VideoMetadata>\n" +
                "        <preprocessor>\n" +
                "            <timesliceclipping>\n" +
                "                <enabled>0</enabled>\n" +
                "                <trimmed>1</trimmed>\n" +
                "            </timesliceclipping>\n" +
                "            <advertisement>\n" +
                clip
                +
                "                <mv4enlight>\n" +
                "                    <totalduration></totalduration>\n" +
                "                    <uri></uri>\n" +
                "                    <programid>-1</programid>\n" +
                "                    <audiotrackid>-1</audiotrackid>\n" +
                "                    <subtitleid>-2</subtitleid>\n" +
                "                    <padding>0</padding>\n" +
                "                    <logouri></logouri>\n" +
                "                    <logoprogramid>-1</logoprogramid>\n" +
                "                    <logoaudiotrackid>-1</logoaudiotrackid>\n" +
                "                    <logosubtitleid>-2</logosubtitleid>\n" +
                "                </mv4enlight>\n" +
                "            </advertisement>\n" +
                "            <audiodelay>0</audiodelay>\n" +
                "        </preprocessor>\n" +
                "    </localfile>\n" +
                "</inputs>\n" +
                "<outputgroups>\n" +
                "    <filearchive >\n" +
                "        <active>1</active>\n" +
                "        <container>MP4</container>\n" +
                "        <mp4setting>\n" +
                "            <fileheadforemost>1</fileheadforemost>\n" +
                "            <audioprocessmode>0</audioprocessmode>\n" +
                "            <splitaudiofile>0</splitaudiofile>\n" +
                "            <targetpath></targetpath>\n" +
                "            <targetname>${II}</targetname>\n" +
                "            <autostartend>0</autostartend>\n" +
                "        </mp4setting>\n" +
                "        <description>输出设定1</description>\n" +
                "        <uri>" + targetDir + "</uri>\n" +
                "        <targetname>" + targetFilename + "</targetname>\n" +
                "        <extension>mp4</extension>\n" +
                "        <segmenttype>0</segmenttype>\n" +
                "        <segmentcontainer></segmentcontainer>\n" +
                "        <segmentname>${starttime}-${id}-${seq}</segmentname>\n" +
                "        <playlistname>${id}</playlistname>\n" +
                "        <playlistnamemode>0</playlistnamemode>\n" +
                "        <usesubdirectories>0</usesubdirectories>\n" +
                "        <singleM3u8>0</singleM3u8>\n" +
                "        <iframeplaylist>0</iframeplaylist>\n" +
                "        <byterangemode>0</byterangemode>\n" +
                "        <playlisttype>0</playlisttype>\n" +
                "        <timecodemode>0</timecodemode>\n" +
                "        <keyrotationcount>0</keyrotationcount>\n" +
                "        <ivfollowssegment>0</ivfollowssegment>\n" +
                "        <keyprovidertype></keyprovidertype>\n" +
                "        <audiogroupenabled>0</audiogroupenabled>\n" +
                "        <drm>\n" +
                "            <type>ARC</type>\n" +
                "            <enabled>0</enabled>\n" +
                "            <version>1</version>\n" +
                "            <contentid></contentid>\n" +
                "            <customerid></customerid>\n" +
                "        </drm>\n" +
                "        <output streamref=\"-1\" >\n" +
                "    <hlsaudiogroupref></hlsaudiogroupref>\n" +
                "    <hlssubtitlegroupref></hlssubtitlegroupref>\n" +
                "        </output>\n" +
                "    </filearchive>\n" +
                "</outputgroups>\n" +
                "</task>";
        return result;
    }
}
